#include "to.h"

namespace YQ {

ImageData
toImageData (const Mat &img)
{
	return ImageData (img.data, img.cols, img.rows, img.channels());
}

ImageData
toImageData (const string &img_file) noexcept (false)
{
	return toImageData (toMat (img_file));
}

Mat
toMat (const ImageData &img)
{
	return Mat (img.height, img.width, CV_8UC (img.channels), img.data);
}

Mat
toMat (const string &img_file) noexcept (false)
{
	Mat img = imread (img_file, cv::ImreadModes::IMREAD_UNCHANGED);
	if (img.empty())
		throw  runtime_error ("无法打开图片" + img_file);
	return img;
}

vector<SeetaFaceInfo>
toVector (const SeetaFaceInfoArray &faces_info)
{
	vector<SeetaFaceInfo>faces;
	for (int i = 0; i < faces_info.size; ++i)
		faces.push_back (faces_info.data[i]);
	return faces;
}

cv::Rect
toCvRect (const SeetaRect &rect)
{
	return cv::Rect (rect.x, rect.y, rect.width, rect.height);
}

QImage
toQImage (const Mat &mat)
{
	cvtColor (mat, mat, cv::COLOR_BGR2RGB);
	return QImage ( (const unsigned char *) mat.data, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
}

Mat
toMat (const QImage &image)
{
    cv::Mat mat;
    switch (image.format()) {
        case QImage::Format_ARGB32:
        case QImage::Format_RGB32:
        case QImage::Format_ARGB32_Premultiplied:
            mat = cv::Mat (image.height(), image.width(), CV_8UC4, (void *) image.bits(), image.bytesPerLine());
            cv::cvtColor (mat, mat, cv::COLOR_RGBA2BGR);
            break;
        case QImage::Format_RGB888:
            mat = cv::Mat (image.height(), image.width(), CV_8UC3, (void *) image.bits(), image.bytesPerLine());
            cv::cvtColor (mat, mat, cv::COLOR_RGB2BGR);
            break;
        case QImage::Format_Indexed8:
            mat = cv::Mat (image.height(), image.width(), CV_8UC1, (void *) image.bits(), image.bytesPerLine());
            break;
    }
    return mat;
}

}
